import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:go_router/go_router.dart';
import '../providers/comic_provider.dart';
import 'widget/header_item_title.dart';

class DiscoverScreen extends ConsumerStatefulWidget {
  const DiscoverScreen({super.key});

  @override
  ConsumerState<DiscoverScreen> createState() => _DiscoverScreenState();
}

class _DiscoverScreenState extends ConsumerState<DiscoverScreen>
    with TickerProviderStateMixin {
  final ScrollController _scrollController = ScrollController();
  double _scrollOffset = 0.0;
  late TabController _tabController;

  final List<String> _genres = [
    'For You',
    'Romance',
    'Adult',
    'Ecchi',
    'Harem',
    'Action',
    'Sci-Fi',
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _genres.length, vsync: this);
    _scrollController.addListener(() {
      setState(() {
        _scrollOffset = _scrollController.offset;
      });
    });

    // 监听 TabController 变化，同步到 provider
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        ref.read(selectedGenreProvider.notifier).state =
            _genres[_tabController.index];
      }
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final selectedGenre = ref.watch(selectedGenreProvider);

    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      body: TabBarView(
        controller: _tabController,
        children: _genres.map((genre) => _buildGenreContent(genre)).toList(),
      ),
    );
  }

  Widget _buildGenreContent(String genre) {
    return CustomScrollView(
      controller: _scrollController,
      slivers: [
        // Banner区域 - 只在 'For You' 标签显示
        if (genre == 'For You')
          SliverToBoxAdapter(
            child: Container(
              height: 280,
              child: Stack(
                fit: StackFit.expand,
                children: [
                  // Banner背景图
                  CachedNetworkImage(
                    imageUrl:
                        'https://ext.same-assets.com/2411567312/2108123692.png',
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      color: const Color(0xFF2A1F3D),
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: const Color(0xFF2A1F3D),
                      child: const Icon(Icons.error, color: Color(0xFF8A7CA8)),
                    ),
                  ),
                  // 渐变遮罩
                  Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          const Color(0xFF211839).withOpacity(0.4),
                          const Color(0xFF211839).withOpacity(0.8),
                        ],
                      ),
                    ),
                  ),
                  // TabBar 覆盖在Banner上方
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Colors.black.withOpacity(0.6),
                            Colors.transparent,
                          ],
                        ),
                      ),
                      child: SafeArea(
                        bottom: false,
                        child: Container(
                          height: 50,
                          child: TabBar(
                            controller: _tabController,
                            isScrollable: true,
                            tabAlignment: TabAlignment.start,
                            indicatorColor: const Color(0xFFFFFFFF),
                            indicatorWeight: 2,
                            labelColor: const Color(0xFFFFFFFF),
                            unselectedLabelColor: const Color(0xFFB8B3C7),
                            labelStyle: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 14,
                            ),
                            unselectedLabelStyle: const TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: 14,
                            ),
                            padding: const EdgeInsets.symmetric(horizontal: 16),
                            tabs: _genres
                                .map((genre) => Tab(text: genre))
                                .toList(),
                          ),
                        ),
                      ),
                    ),
                  ),
                  // EXCLUSIVE CLUB标题
                  Positioned(
                    bottom: 20,
                    left: 20,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'EXCLUSIVE CLUB',
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                        SizedBox(height: 8),
                        Text(
                          'Premium content for members',
                          style: TextStyle(
                            fontSize: 14,
                            color: Color(0xFFB8B3C7),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),

        // 根据 genre 显示不同内容
        _buildGenreSpecificContent(genre),

        // 底部间距
        const SliverToBoxAdapter(
          child: SizedBox(height: 100),
        ),
      ],
    );
  }

  Widget _buildGenreSpecificContent(String genre) {
    // 使用 comicsByGenreProvider 获取特定类型的漫画
    final comics = ref.watch(comicsByGenreProvider(genre));

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          if (index >= comics.length) return null;
          final comic = comics[index];
          return _buildDetailedComicItem(comic);
        },
        childCount: comics.length,
      ),
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required Color color,
    // 添加点击事件
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.2), // 增加透明度以适应深色背景
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(
              icon,
              color: color,
              size: 24,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            label,
            style: const TextStyle(
              fontSize: 12,
              color: Color(0xFFB8B3C7), // 浅紫灰色文字
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionHeader(String title) {
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 24, 16, 12),
        child: Row(
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Color(0xFFFFFFFF), // 白色标题
              ),
            ),
            const Spacer(),
            Text(
              'More >',
              style: TextStyle(
                fontSize: 14,
                color: const Color(0xFF8A7CA8), // 中等紫灰色
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHorizontalComicList() {
    final comics = ref.watch(comicsProvider);

    return SliverToBoxAdapter(
      child: SizedBox(
        height: 140,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          itemCount: comics.length,
          itemBuilder: (context, index) {
            final comic = comics[index];
            return Container(
              width: 100,
              margin: const EdgeInsets.only(right: 12),
              child: Column(
                children: [
                  Expanded(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: CachedNetworkImage(
                        imageUrl: comic.coverImageUrl,
                        fit: BoxFit.cover,
                        width: double.infinity,
                        placeholder: (context, url) => Container(
                          color: const Color(0xFF2A1F3D),
                        ),
                        errorWidget: (context, url, error) => Container(
                          color: const Color(0xFF2A1F3D),
                          child:
                              const Icon(Icons.error, color: Color(0xFF8A7CA8)),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    comic.title,
                    style: const TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFFB8B3C7), // 浅紫灰色文字
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildGridComicList() {
    final comics = ref.watch(comicsProvider);

    return SliverPadding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      sliver: SliverGrid(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            if (index >= 6) return null; // 只显示6个
            final comic = comics[index % comics.length];
            return _buildGridComicItem(comic);
          },
          childCount: 6,
        ),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 0.7,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
        ),
      ),
    );
  }

  Widget _buildGridComicItem(comic) {
    return GestureDetector(
      onTap: () => context.push('/comic/${comic.id}'),
      child: Column(
        children: [
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: comic.coverImageUrl,
                fit: BoxFit.cover,
                width: double.infinity,
                placeholder: (context, url) => Container(
                  color: const Color(0xFF2A1F3D),
                ),
                errorWidget: (context, url, error) => Container(
                  color: const Color(0xFF2A1F3D),
                  child: const Icon(Icons.error, color: Color(0xFF8A7CA8)),
                ),
              ),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            comic.title,
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFFB8B3C7), // 浅紫灰色文字
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildVerticalComicList() {
    final comics = ref.watch(comicsProvider);

    return SliverToBoxAdapter(
      child: Column(
        children: [
          // 大的特色项目
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: _buildFeaturedComicItem(comics.first),
          ),
          const SizedBox(height: 16),
          // 横向滚动列表
          SizedBox(
            height: 140,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: comics.length - 1,
              itemBuilder: (context, index) {
                final comic = comics[index + 1]; // 跳过第一个（特色项目）
                return Container(
                  width: 100,
                  margin: const EdgeInsets.only(right: 12),
                  child: _buildSmallComicItem(comic),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFeaturedComicItem(comic) {
    return GestureDetector(
      onTap: () => context.push('/comic/${comic.id}'),
      child: Container(
        height: 120,
        child: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: comic.coverImageUrl,
                width: 90,
                height: 120,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  width: 90,
                  height: 120,
                  color: const Color(0xFF2A1F3D),
                ),
                errorWidget: (context, url, error) => Container(
                  width: 90,
                  height: 120,
                  color: const Color(0xFF2A1F3D),
                  child: const Icon(Icons.error, color: Color(0xFF8A7CA8)),
                ),
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    comic.title,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFFFFFFFF), // 白色标题
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    comic.author,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Color(0xFF8A7CA8), // 中等紫灰色
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSmallComicItem(comic) {
    return GestureDetector(
      onTap: () => context.push('/comic/${comic.id}'),
      child: Column(
        children: [
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: comic.coverImageUrl,
                fit: BoxFit.cover,
                width: double.infinity,
                placeholder: (context, url) => Container(
                  color: const Color(0xFF2A1F3D),
                ),
                errorWidget: (context, url, error) => Container(
                  color: const Color(0xFF2A1F3D),
                  child: const Icon(Icons.error, color: Color(0xFF8A7CA8)),
                ),
              ),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            comic.title,
            style: const TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.w500,
              color: Color(0xFFB8B3C7), // 浅紫灰色文字
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildDetailedComicList() {
    final comics = ref.watch(comicsProvider);

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          if (index >= comics.length) return null;
          final comic = comics[index];
          return _buildDetailedComicItem(comic);
        },
        childCount: comics.length,
      ),
    );
  }

  Widget _buildDetailedComicItem(comic) {
    return GestureDetector(
      onTap: () => context.push('/comic/${comic.id}'),
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: comic.coverImageUrl,
                width: 80,
                height: 100,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  width: 80,
                  height: 100,
                  color: const Color(0xFF2A1F3D),
                ),
                errorWidget: (context, url, error) => Container(
                  width: 80,
                  height: 100,
                  color: const Color(0xFF2A1F3D),
                  child: const Icon(Icons.error, color: Color(0xFF8A7CA8)),
                ),
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    comic.title.toUpperCase(),
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFFFFFFFF), // 白色标题
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 4),
                  Text(
                    comic.title,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Color(0xFF8A7CA8), // 中等紫灰色
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Icon(
                        Icons.star,
                        color: Colors.amber[700],
                        size: 16,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        comic.rating.toString(),
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: Color(0xFFB8B3C7), // 浅紫灰色
                        ),
                      ),
                      const SizedBox(width: 16),
                      Text(
                        '${comic.chaptersCount} chapters',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF8A7CA8), // 中等紫灰色
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
